if(files.cwd().endsWith("脚本")){
  let _require = require;
  require = function(path){
    if(path.startsWith("./")){
      path = path.replace("./","");
    }
    path = files.cwd() + "/gdt_hb/" + path;
    return _require(path);
  }
}


auto.waitFor()
var utils = require("./utils.js");
var storage = storages.create("xiangxiangyuedu");
var time = random(2000, 3000)

function launchAppEnhance(app_name) {
  let thread = threads.start(function () {
    toastLog("检查是否有打开权限!");
    while (true) {
      var allow = text("允许").findOne(5000);
      if (allow) {
        sleep(1000)
        toastLog("发现允许授权!");
        allow.click();
        sleep(1000);
        thread.interrupt();
        break;
      }
    }
  });
  sleep(1000);
  var result = launchApp(app_name);
  sleep(3000);
  thread.interrupt();
  return result;
}

function 广告() {
  let try_count = 11, close_btn = null;
  while (!close_btn) {
    if (try_count <= 0) {
      break
    }
    // 直到找到关闭按钮
    close_btn = className('android.widget.ImageView').clickable().depth(1).drawingOrder(3).findOne(1000) ||
      idContains("ad_close").findOne(1000) ||
      className('android.widget.ImageView').clickable().depth(5).drawingOrder(2).findOne(1000)
    if (close_btn) {
      close_btn.click()
      sleep(time)
      break
    } else {
      try {
        取消 = text("取消").findOne(500)
        if (取消) {
          点击控件(取消)
        }
      } catch (error) { }
      try {
        关闭 = text("关闭").findOne(500)
        if (关闭) {
          点击控件(关闭)
        }
      } catch (error) { }
      try {//支付宝
        if (currentPackage() != 'com.yfsj.mh') {
          toastLog('应该是到支付宝界面了')
          sleep(2000)
          back()
          sleep(500)
          back()
          sleep(2000)
          继续 = textStartsWith("继续").findOne(1000)
          if (继续) {
            点击控件(继续)
          }
          var 任务中心 = text('任务中心').findOne(3000)
          if (任务中心) {
            break
          }
        }
      } catch (error) { }
    }
    try_count--
    sleep(2000)
  }
}

function openScreenCapture() {
  let thread1 = threads.start(function () {
    toastLog("检查请求截屏!")
    var began = text("立即开始").findOne();
    if (began) {
      sleep(1000)
      toastLog("发现请求截屏！");
      began.click();
      sleep(1000);
      thread1.interrupt();
    }
  });
  sleep(1000);
  if (!requestScreenCapture()) {
    toastLog("请求截图失败!");
    exit();
  }
  else {
    toastLog("请求截图成功!");
  }
}

function 过滑块() {
  dragSlider()
  function dragSlider() {
    滑块 = text('tag-bar').findOne(2000)
    if (滑块) {
      sleep(time)
      toastLog("找到滑块")
      拖动滑块x = 滑块.bounds().centerX()
      拖动滑块y = 滑块.bounds().centerY()
      sleep(time)
      for (var i = 0; i < 0; i++) { sleep(1000); log(i); }
      while (true) {
        img = images.captureScreen();
        if (img) {
          log("截图成功。进行识别滑块！");
          break;
        } else {
          log('截图失败,重新截图');
        }
      }
      if (device.model == 'Redmi 8A') {
        var x = discernSlidingblock(img, device.width) + 40
      }
      if (device.model == 'MI 5X') {
        var x = discernSlidingblock(img, device.width) - 190
      }
      toastLog("识别结果滑块X坐标：" + x);
      if (x > -1) {
        randomSwipe(拖动滑块x, 拖动滑块y, x, 拖动滑块y)
        return true;
      } else {
        return false;
        console.log("识别有误，请确认是否在滑块界面");
      }
    }
    else {
      toastLog("没找到滑块")
    }
  }

  /**
  * 计算滑块位置
  * @param {图片} img
  * @param {分辨率} ratio
  */
  function discernSlidingblock(img, ratio) {
    //创建识别变量
    var temp, temp2, x, y, num, color, p, temp3, arr1;
    //分析设备分辨率
    //红米8A
    if (ratio == 720) {
      var tb = [485, 572, 684, 943]
      log("您的设备分辨率为：720p");
    } else if (ratio == 1080) {  //小米5X
      var tb = [756, 670, 1026, 1232]
      log("您的设备分辨率为：1080p");
    } else {
      log("当前设备分辨率不符合规范")
      return -2
    }
    num = Math.ceil(tb[4] / 3.3 - 4);

    //计算滑块位置
    for (var k = 29; k <= 40; k++) {
      temp2 = "";
      color = "#" + k + "" + k + "" + k + "";
      for (var i = 1; i <= num; i++) {
        temp2 = temp2 + "0|" + i + "|" + color + ",";
        temp2 = temp2 + i + "|0|" + color + ",";
        temp2 = temp2 + "1|" + i + "|" + color + ",";
        temp2 = temp2 + i + "|1|" + color + ",";
        temp2 = temp2 + "2|" + i + "|" + color + ",";
        temp2 = temp2 + i + "|2|" + color + ",";
      }
      x = 0;
      while (x > -2) {
        y = 0;
        while (y > -2) {
          temp = "";
          for (var i = 1; i <= num; i += 2) {
            temp = temp + "0|" + (tb[4] + y - i - 1) + "|" + color + ",";
            temp = temp + (tb[4] + x) + "|" + i + "|" + color + ",";
            temp = temp + (tb[4] + x) + "|" + (tb[4] + y - i - 1) + "|" + color + ",";
            temp = temp + (tb[4] + x - i - 1) + "|0|" + color + ",";
            temp = temp + i + "|" + (tb[4] + y) + "|" + color + ",";
            temp = temp + (tb[4] + x - i - 1) + "|" + (tb[4] + y) + "|" + color + ",";
            temp = temp + "1|" + (tb[4] + y - i - 1) + "|" + color + ",";
            temp = temp + (tb[4] + x - 1) + "|" + i + "|" + color + ",";
            temp = temp + (tb[4] + x - 1) + "|" + (tb[4] + y - i - 1) + "|" + color + ",";
            temp = temp + (tb[4] + x - i - 1) + "|1|" + color + ",";
            temp = temp + i + "|" + (tb[4] + y - 1) + "|" + color + ",";
            temp = temp + (tb[4] + x - i - 1) + "|" + (tb[4] + y - 1) + "|" + color + ",";
          }
          temp = temp + temp2 + "0|0|" + color;
          arr1 = temp.split(",");
          var arr2 = new Array();
          for (var i = 0; i < arr1.length - 1; i++) {
            arr2[i] = new Array();
            temp3 = arr1[i].split("|");
            arr2[i] = [Number(temp3[0]), Number(temp3[1]), temp3[2]];
          }
          try {
            p = images.findMultiColors(img, color, arr2, {
              region: [tb[0], tb[1], tb[2] - tb[0], tb[3] - tb[1]],
              threshold: (Math.floor(k / 10) * 16 + k % 10)
            });
            if (p) {
              img.recycle();
              return p.x
            }
          } catch (error) {
            //出错
            console.log("识别失败，错误原因：" + error);
            return -1;
          }
          y = --y;
        }
        x = --x;
      }
    }
    try {
      img.recycle();
    } catch (error) {
      console.log("识别失败，错误原因：" + error);
    }
    return -1;
  }

  /**
  * 真人模拟滑动函数 （滑块滑动）
  * @param {起点x} sx
  * @param {起点y} sy
  * @param {终点x} ex
  * @param {终点y} ey
  */
  function randomSwipe(sx, sy, ex, ey) {
    //设置随机滑动时长范围
    var timeMin = 1000
    var timeMax = 3000
    //设置控制点极限距离
    var leaveHeightLength = 500

    //根据偏差距离，应用不同的随机方式
    if (Math.abs(ex - sx) > Math.abs(ey - sy)) {
      var my = (sy + ey) / 2
      var y2 = my + random(0, leaveHeightLength)
      var y3 = my - random(0, leaveHeightLength)

      var lx = (sx - ex) / 3
      if (lx < 0) { lx = -lx }
      var x2 = sx + lx / 2 + random(0, lx)
      var x3 = sx + lx + lx / 2 + random(0, lx)
    } else {
      var mx = (sx + ex) / 2
      var y2 = mx + random(0, leaveHeightLength)
      var y3 = mx - random(0, leaveHeightLength)

      var ly = (sy - ey) / 3
      if (ly < 0) { ly = -ly }
      var y2 = sy + ly / 2 + random(0, ly)
      var y3 = sy + ly + ly / 2 + random(0, ly)
    }

    //获取运行轨迹，及参数
    var time = [0, random(timeMin, timeMax)]
    var track = bezierCreate(sx, sy, x2, y2, x3, y3, ex, ey)


    log("随机控制点A坐标：" + x2 + "," + y2)
    log("随机控制点B坐标：" + x3 + "," + y3)
    log("随机滑动时长：" + time[1])

    //滑动
    gestures(time.concat(track))
  }

  /**
  * 计算滑动轨迹
  */
  function bezierCreate(x1, y1, x2, y2, x3, y3, x4, y4) {
    //构建参数
    var h = 100;
    var cp = [{ x: x1, y: y1 + h }, { x: x2, y: y2 + h }, { x: x3, y: y3 + h }, { x: x4, y: y4 + h }];
    var numberOfPoints = 100;
    var curve = [];
    var dt = 1.0 / (numberOfPoints - 1);

    //计算轨迹
    for (var i = 0; i < numberOfPoints; i++) {
      var ax, bx, cx;
      var ay, by, cy;
      var tSquared, tCubed;
      var result_x, result_y;

      cx = 3.0 * (cp[1].x - cp[0].x);
      bx = 3.0 * (cp[2].x - cp[1].x) - cx;
      ax = cp[3].x - cp[0].x - cx - bx;
      cy = 3.0 * (cp[1].y - cp[0].y);
      by = 3.0 * (cp[2].y - cp[1].y) - cy;
      ay = cp[3].y - cp[0].y - cy - by;

      var t = dt * i
      tSquared = t * t;
      tCubed = tSquared * t;
      result_x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
      result_y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
      curve[i] = {
        x: result_x,
        y: result_y
      };
    }

    //轨迹转路数组
    var array = [];
    for (var i = 0; i < curve.length; i++) {
      try {
        var j = (i < 100) ? i : (199 - i);
        xx = parseInt(curve[j].x)
        yy = parseInt(Math.abs(100 - curve[j].y))
      } catch (e) {
        break
      }
      array.push([xx, yy])
    }

    return array
  }
}

// 点击控件坐标，控件的clickbale为false的时候
function 点击控件(x) {
  var weight = x.bounds()
  click(weight.centerX(), weight.centerY())
}

function restart() {
  home();
  sleep(1000);
  recents();
  let clear = id("clearAnimView").findOne(2000);
  if (clear) {
    sleep(1000);
    log("清除后台程序");
    clear.click();
  }
  var open_app = launchAppEnhance("影粉世家极速版");
  sleep(5000)
  if (open_app) {
    toastLog("重启成功")
  }
}

// 随机向上滑动
function swip_up() {
  var w = device.width
  var h = device.height

  function bezier_curves(cp, t) {
    cx = 3.0 * (cp[1].x - cp[0].x);
    bx = 3.0 * (cp[2].x - cp[1].x) - cx;
    ax = cp[3].x - cp[0].x - cx - bx;
    cy = 3.0 * (cp[1].y - cp[0].y);
    by = 3.0 * (cp[2].y - cp[1].y) - cy;
    ay = cp[3].y - cp[0].y - cy - by;

    tSquared = t * t;
    tCubed = tSquared * t;
    result = { "x": 0, "y": 0 };
    result.x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
    result.y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
    return result;
  };


  function sml_move(qx, qy, zx, zy, time) {
    //仿真随机带曲线滑动: qx, qy, zx, zy, time 代表起点x,起点y,终点x,终点y,过程耗时单位毫秒
    var xxy = [time];
    var point = [
      { "x": qx, "y": qy },
      { "x": random(qx - 100, qx + 100), "y": random(qy, qy + 50) },
      { "x": random(zx - 100, zx + 100), "y": random(zy, zy + 50) },
      { "x": zx, "y": zy }
    ];
    for (let i = 0; i < 1; i += 0.08) {
      xxyy = [parseInt(bezier_curves(point, i).x), parseInt(bezier_curves(point, i).y)]
      xxy.push(xxyy);
    }
    gesture.apply(null, xxy);
  }

  sml_move(w / 2, h * 0.8 + h * random() * 0.1, w / 2, h * 0.15, 200 + 600 * random());
}

function login() {
  sleep(time)
  toastLog('当前在登录界面')
  sleep(time)
  var 请输入账号 = text('请输入账号').findOne(5000)
  if (请输入账号) {
    请输入账号.click()
    sleep(time)
    if (device.model == 'Redmi 8A') {
      sleep(time)
      click(random(86, 640), random(530, 606))
    }
    if (device.model == 'MI 5X') {
      sleep(time)
      click(random(183, 962), random(752, 861))
    }
    sleep(time)
    var arr = text('登录').find()
    if (arr.length > 0) {
      arr[1].parent().click()
      sleep(4000)
      var 滑块 = text('tag-bar').findOne(5000)
      if (滑块) {
        var j = 1
        openScreenCapture()
        while (j < 4) {
          sleep(4000)
          toastLog('第' + j + '次尝试过滑块')
          sleep(time)
          captureScreen()
          过滑块()
          var 任务中心 = text('任务中心').findOne(5000)
          if (任务中心) {
            toastLog('滑块验证成功')
            sleep(time)
            j = 5
          } else {
            toastLog('重新尝试')
            sleep(time)
            if (device.model == 'Redmi 8A') {
              click(random(556, 602), random(1058, 1104))
            }
            if (device.model == 'MI 5X') {
              click(random(834, 903), random(1404, 1473))
            }
            sleep(time)
          }
          j++
        }
      }
    }
  }
}

function task() {
  var 个人中心 = text('个人中心').findOne(30000)
  if (个人中心) {
    sleep(5000)
    var 任务中心 = text('任务中心').findOne(5000)
    if (任务中心) {
      任务中心.parent().click()
      sleep(time)
    }
    var 登录 = text('登录').findOne(5000)
    if (登录) {
      login()
      var 任务中心 = text('任务中心').findOne(5000)
      if (任务中心) {
        任务中心.parent().click()
        sleep(8000)
        var arr = className('android.view.ViewGroup').clickable().depth(7).find()
        if (arr.length > 0) {
          arr[1].click()
          sleep(time)
          var 领取 = text('领取').findOne(5000)
          if (领取) {
            领取.parent().click()
            sleep(8000)
          }
          var arr = className('android.view.ViewGroup').clickable().depth(7).find()
          if (arr.length > 0) {
            arr[1].click()
            sleep(time)
          }
        }
      }
    } else {
      toastLog('当前已经在任务界面')
      sleep(5000)
      var arr = className('android.view.ViewGroup').clickable().depth(7).find()
      if (arr.length > 0) {
        arr[1].click()
        sleep(time)
        var 领取 = text('领取').findOne(5000)
        if (领取) {
          领取.parent().click()
          sleep(8000)
        }
        var arr = className('android.view.ViewGroup').clickable().depth(7).find()
        if (arr.length > 0) {
          arr[1].click()
          sleep(time)
        }
      }
    }

    var index = 1
    while (index < 8) {
      log("进入[看视频得粉钻],开始第 " + index + "个视频")
      var 看视频得粉钻 = text('看视频得粉钻').findOne(1000)
      if (看视频得粉钻) {
        var finalActivity = currentActivity();
        看视频得粉钻.parent().click()
        sleep(5000)
        var 粉钻任务 = text('粉钻任务').findOne(1000)
        if (!粉钻任务) {
          toastLog('当前是广告页面')
          utils.waitAdvert(finalActivity);
          var closeBtn = className('android.view.ViewGroup').clickable().depth(7).findOne(10000)
          if (closeBtn) {
            closeBtn.click()
            sleep(time)
          }
        }
      } else {
        toastLog('已经完成任务')
        sleep(time)
        break
      }
      index++
      if(index*12.5 < 100){
        utils.updateAppProgress(index*12.5);
      }
    }
    var close_y = className('android.view.ViewGroup').clickable().depth(15).findOne(5000)
    if (close_y) {
      close_y.click()
      sleep(time)
    }
    var close_z = className('android.view.ViewGroup').clickable().depth(7).drawingOrder(3).findOne(5000)
    if (close_z) {
      close_z.click()
      sleep(time)
    }
  }
}


function 新人任务(){
  for(var i = 0;i<10;i++){
    var tt = className('android.view.ViewGroup').clickable().depth(26).findOne(5000)
    if(tt){
      tt.click();
      广告()
      var arr = className('android.view.ViewGroup').clickable(true).depth(7).findOne(3000)
      //log("arr:" + arr);
      if (arr) {
        arr.click()
        sleep(time)
      }
    }
  }
  
}

function 转盘() {
  var 免费转粉钻 = text('免费转粉钻').findOne(5000)
  if (免费转粉钻) {
    免费转粉钻.parent().click()
    sleep(5000)
    var i = 0
    while (i < 6) {
      var 立即抽奖 = text("立即抽奖").findOne(1000)
      if (立即抽奖) {
        点击控件(立即抽奖)
        sleep(5000)
        var 立即抽奖 = text("立即抽奖").findOne(1000)
        if (!立即抽奖) {
          toastLog('当前是广告界面')
          广告()
          sleep(8000)
          var arr = className('android.view.ViewGroup').clickable().depth(7).find()
          if (arr.length > 0) {
            arr[1].click()
            sleep(time)
          }
        }
      } else {
        toastLog('完成任务')
        sleep(time)
        break
      }
      i++
    }
  }
}

function main() {
  let open_app = launchAppEnhance("影粉世家极速版");
  if (open_app) {
    var thread_1 = threads.start(function () {
      toastLog("检查广告弹窗")
      while (true) {
        var widget = text('知道了~').findOne(1000)
        if (widget) {
          点击控件(widget)
          sleep(time)
        }
      }
    })
    task()
    log("完成视频任务.")
    新人任务()
    log("完成新人任务")
    转盘()
    log("完成转盘任务")
  
    thread_1.interrupt()
  }
  else {
    toastLog("影粉世家极速版打开失败，请确认是否安装并授权打开!");
  }
}

try {
  main();
  utils.updateAppProgress(100);
} catch (error) {
  toastLog(error);
}

storage.put("script_running_status", "end");